﻿using Castle.DynamicProxy;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ALEXBlog.Extensions.Interceptors
{
    public class LoggerInterceptor : IInterceptor
    {
        static ReaderWriterLockSlim LockSlim = new ReaderWriterLockSlim();
        private static string InterceptLogInfo(IInvocation invocation)
        {
            return $"【{DateTime.Now.ToString("yyyyMMddHHmmss")}】 \r\n " +
                $"【当前工作函数】:{ invocation.Method.Name }\r\n " +
                $"【函数携带参数】:{ string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())}\r\n "
                + $"【方法完成返回值】:{ invocation.ReturnValue }\r\n ";
        }

        private static Task WriteLog(string logText)
        {
            return Task.Run(() =>
            {
                LockSlim.EnterWriteLock();
                #region 输出到当前项目日志
                var path = Directory.GetCurrentDirectory() + @"\Log";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string fileName = path + $@"\InterceptLog-{DateTime.Now.ToString("yyyyMMdd")}.log";
                using (StreamWriter sw = File.AppendText(fileName))
                {
                    sw.WriteLine(logText);
                }
                #endregion
                LockSlim.ExitWriteLock();
            });
        }

        public void Intercept(IInvocation invocation)
        {
            invocation.Proceed();
            var logInfo = InterceptLogInfo(invocation);
            WriteLog(logInfo);
        }
    }
}
